package com.baichang.taoshunda.service.impl;

import com.alipay.api.AppPay;
import com.baichang.framework.excelption.ServiceException;
import com.baichang.framework.model.Page;
import com.baichang.framework.utils.KidUtils;
import com.baichang.taoshunda.dao.*;
import com.baichang.taoshunda.entity.BusinessMoneyRecord;
import com.baichang.taoshunda.entity.Bussiness;
import com.baichang.taoshunda.service.BusinessMoneyRecordService;
import com.weixin.pay.api.WeixinPay;
import com.weixin.pay.api.model.PayInfo;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2018/2/24 0024.
 */
@Service
public class BusinessMoneyRecordServiceImpl implements BusinessMoneyRecordService {

    @Autowired
    private BusinessMoneyRecordDao businessMoneyRecordDao;

    @Autowired
    private BussinessDao bussinessDao;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private HtmlDao htmlDao;

    /**
     * 保证金查询
     *
     * @param busId
     * @param typeId
     * @param is
     * @return
     */
    @Override
    public Map<String, Object> queryTypeMoney(Integer busId, Integer typeId, Integer is) {
        Map map = new HashedMap();
        Map<String, Object> bus = businessMoneyRecordDao.getRecordInfo(busId, is);
        String num;
        if (bus == null) {
            num = "0";
        } else {
            num = bus.get("num").toString();
        }
        if (num.equals("1")) {
            map.put("ifPayment", 1);
            map.put("status", bus.get("status"));
            map.put("id", bus.get("id"));
        } else {
            map.put("ifPayment", 0);
            map.put("status", 0);
        }
        Map<String, Object> record = businessMoneyRecordDao.queryTypeMoney(typeId, is);
        map.put("money", record.get("money"));
        Map<String, Object> notice = htmlDao.getInfo(is);
        map.put("value", notice.get("value"));
        return map;
    }

    /**
     * @param busId
     * @param payType
     * @param money
     * @return
     */
    @Override
    public Map<String, Object> payDeposit(Integer busId, Integer payType, BigDecimal money) {
        String kid = KidUtils.getKKid();
        Map map = new HashedMap();
        Bussiness business = bussinessDao.getEntityById(busId);
        String title = business.getBussName() + "付款:" + money + "元";
        boolean isTrue = false;
        //1支付宝、2微信
        if (payType == 1) {
            //支付宝
            String aplipay = AppPay.createPay(title, kid, title, money.doubleValue());//这里传的是支付订单编号
            map.put("pay", aplipay);
        } else if (payType == 2) {
            int price = money.multiply(BigDecimal.valueOf(100)).intValue();
            WeixinPay weixinPay = new com.weixin.pay.api.AppPay();
            PayInfo payInfo = new PayInfo();
            payInfo.setBody(title);
            payInfo.setTradeNo(kid);
            payInfo.setSubject(title);
            payInfo.setPrice(price);
            payInfo.loadWxConfig("wx48217cb07b14d413");
            weixinPay.setPayInfo(payInfo);
            map = weixinPay.createPay();
        }
        return map;
    }

    /**
     * @param busId
     * @param payType
     * @param money
     * @param type
     * @return
     */
    @Override
    public boolean successPayDeposit(Integer busId, Integer payType, BigDecimal money, Integer type) {
        BusinessMoneyRecord businessMoneyRecord = new BusinessMoneyRecord();
        businessMoneyRecord.setStatus(1);
        businessMoneyRecord.setCreatedTime(new Date());
        businessMoneyRecord.setMoney(money);
        businessMoneyRecord.setBuinessUd(busId);
        businessMoneyRecord.setPayType(payType);
        businessMoneyRecord.setType(type); //1.假一罚三  2.消费者
        return businessMoneyRecordDao.save(businessMoneyRecord) > 0;
    }

    /**
     * @param id
     * @param busId
     * @param money
     * @param type
     * @return
     */
    @Override
    public boolean returnDepositMoney(Integer id, Integer busId, BigDecimal money, Integer type) throws ServiceException, ParseException {
        Bussiness business = bussinessDao.getEntityById(busId);
        BigDecimal allMoney;
        boolean a = false;
        //是否还有在线的商品
        if (type == 2) {
            Map<String, Object> map = goodsDao.getGoodsUpperNum(busId);
            String num = map.get("num").toString();
            int nums = Integer.parseInt(num);
            if (nums > 0) {
                throw new ServiceException("您的店铺还有未删除的商品，不能退还保障金");
            }
            //查询有未完成的订单或者退款、退货的订单
            Map<String, Object> maps = orderDao.getOrderNum(busId);
            String number = maps.get("num").toString();
            int numbers = Integer.parseInt(number);
            if (numbers > 0) {
                throw new ServiceException("店铺内有订单为已签收或者退款未成功状态，不能退还保障金");
            }
            //获取最大订单时间是否满足30天
            Map<String, Object> setMap = orderDao.getOrderMaxCreated(busId);
            String time = setMap.get("times").toString();
            if (time.equals("0")) {
                a = businessMoneyRecordDao.updateStatus(id, 2) > 0;
            } else {
                //最大时间
                Date present = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                Date ddate = sdf.parse(time);
                Calendar calc = Calendar.getInstance();
                calc.setTime(ddate);
                calc.add(Calendar.DATE, 30);
                String minDateStr = sdf.format(calc.getTime());
                //将字符串转换为date类型
                Date dt1 = sdf.parse(minDateStr);//最大订单时间的30天后的时间
                //当前系统时间等于 商家订单最大时间的30天  可通过
                if (present.getTime() == dt1.getTime()) {
                    allMoney = business.getBalance().add(money);
                    //退款商家余额
                    bussinessDao.updateBalance(busId, allMoney);
                    a = businessMoneyRecordDao.updateStatus(id, 2) > 0;
                } else {
                    throw new ServiceException("最后一笔订单完成之次日起未满30天，不能退还保障金");
                }
            }
        } else {
            allMoney = business.getBalance().add(money);
            //退款商家余额
            bussinessDao.updateBalance(busId, allMoney);
            a = businessMoneyRecordDao.updateStatus(id, 2) > 0;
        }
        return a;
    }

    /**
     * 查询需要审核的保证金
     *
     * @param businessName
     * @param nowPage
     * @param pageSize
     * @return
     */
    @Override
    public Page queryAuditingDepsoit(String businessName, int nowPage, int pageSize) {
        return businessMoneyRecordDao.queryAuditingDepsoit(businessName, nowPage, pageSize);
    }

    /**
     * 同意审核
     *
     * @param id
     * @return
     */
    @Override
    public boolean updateStatus(Integer id) {
        return businessMoneyRecordDao.updateStatus(id, 3) > 0;
    }

    /**
     * 查询保证金的记录
     *
     * @param businessName
     * @param nowPage
     * @param pageSize
     * @return
     */
    @Override
    public Page queryRecord(String businessName, int nowPage, int pageSize) {
        return businessMoneyRecordDao.queryRecord(businessName, nowPage, pageSize);
    }
}
